package service

import (
	"fly/models"
	"github.com/beego/beego/v2/client/orm"
	"github.com/duke-git/lancet/v2/slice"
)

type SysRoleUserService struct {
	BaseService
}

func (c *SysRoleUserService) SaveOrUpdate(userId int64, roleIdList []int64, operator int64) (err error) {
	//先删除角色菜单关系
	_, err = orm.NewOrm().QueryTable(new(models.SysRoleUser)).Filter("user_id", userId).Delete()
	if len(roleIdList) == 0 {
		return nil
	}
	o := orm.NewOrm()
	for _, roleId := range roleIdList {
		_, err = o.Insert(&models.SysRoleUser{
			BaseModel: models.BaseModel{Creator: operator},
			RoleId:    roleId,
			UserId:    userId,
		})
	}
	return
}

func (c *SysRoleUserService) GetRoleIdListByUserId(userId int64) ([]int64, error) {
	var list []*models.SysRoleUser
	_, err := orm.NewOrm().QueryTable(new(models.SysRoleUser)).Filter("user_id", userId).All(&list, "role_id")
	if err != nil {
		return []int64{}, err
	}
	ids := slice.Map(list, func(index int, item *models.SysRoleUser) int64 {
		return item.RoleId
	})
	return ids, nil
}
